package com.pqtest.api.controller;

import com.pqtest.api.annotation.ResponseFormat;
import com.pqtest.api.dto.AccountDto;
import com.pqtest.api.dto.JwtDto;
import com.pqtest.api.service.JwtService;
import com.pqtest.api.service.UserService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@Log
public class AccountController {
    @Autowired
    UserService userService;
    @Autowired
    JwtService jwtService;
    @PostMapping("/account/register")
    @ResponseFormat(type="withSingle")
    public Object register(@Valid AccountDto accountDto, BindingResult bindingResult) throws Exception {
        if(bindingResult.hasErrors()){
            throw new Exception(bindingResult.getFieldError().getDefaultMessage());
        }
        return userService.register(accountDto);
    }

    @PutMapping("/account/password")
    @ResponseFormat(type="withSingle")
    public Object updatePassword(@Valid AccountDto accountDto,BindingResult bindingResult,OAuth2Authentication oAuth2Authentication) throws Exception {
        JwtDto jwtDto = jwtService.getUser(oAuth2Authentication);
        accountDto.setName(jwtDto.getName());
        accountDto.setSalt("");
        return userService.changePassword(accountDto);
    }

    @PutMapping("/account/category")
    @ResponseFormat(type="withSingle")
    public Object updateCategory(@Valid AccountDto accountDto,BindingResult bindingResult) throws Exception {
        if(bindingResult.hasErrors()){
            throw new Exception(bindingResult.getFieldError().getDefaultMessage());
        }
        return userService.updateCategory(accountDto);
    }
}
